package xxl.robotlegs.extensions.modularity.impl 
{
	import flash.display.DisplayObjectContainer;
	import xxl.robotlegs.framework.api.IContext;
	import xxl.robotlegs.framework.api.ILogger;
	/**
	 * ...
	 * @author XXL
	 */
	public class ContextViewBasedExistenceWatcher 
	{
		private var _context:IContext;
		private var _contextView:DisplayObjectContainer;
		private var _logger:ILogger;
		
		public function ContextViewBasedExistenceWatcher(context:IContext, contextView:DisplayObjectContainer) 
		{
			_context = context;
			_contextView = contextView;
			_logger = context.getLogger(this);
			context.whenDestroying(destroy);
			init();
		}
		
		private function init():void
		{
			_logger.debug("在contextView {0} 上添加一个context是否存在的监听", [_contextView]);
			_contextView.addEventListener(ModularContextEvent.CONTEXT_ADD, onContextAdd);
		}
		
		private function destroy():void
		{
			_logger.debug("删除contextView {0} 上context是否存在的监听", [_contextView]);
			_contextView.removeEventListener(ModularContextEvent.CONTEXT_ADD, onContextAdd);
		}
		
		private function onContextAdd(event:ModularContextEvent):void 
		{
			const context:IContext = event.context;
			if (context != _context)
			{
				event.stopImmediatePropagation();
				_logger.debug("配置子context {0}", [context]);
				_context.addChild(context);
			}
		}
		
	}

}